<template>
  <div style="border-top: 1px solid #333; margin: 20px 0;"></div>
    <div id="app">
      <el-card class="register-card">
        <h2 class="title">用户注册</h2>
        <div class="register-content">
          <div class="avatar-upload">
      <el-upload
        class="upload-demo"
        action="https://your-server/upload-avatar" 
        :before-upload="beforeUpload"
        :on-success="handleUploadSuccess"
        :http-request="customRequest"
        list-type="picture-card"
        :show-file-list="false"
      >
        <img v-if="imageUrl" :src="imageUrl" alt="avatar" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
      <!-- <el-button type="primary" @click="handleConfirm" :disabled="!selectedFile">
        确认上传
      </el-button> -->
    </div>

        



    <div class="form-container">

        <el-form
          ref="registerForm"
          :model="form"
          :rules="rules"
          label-width="80px"
          class="register-form"
        >
        <el-form-item label="姓名" prop="name" class="form-item">
            <el-input
              v-model="form.username"
              placeholder="请输入姓名"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="telephone" class="form-item">
            <el-input
              v-model="form.telephone"
              placeholder="请输入手机号"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password" class="form-item">
            <el-input
              v-model="form.password"
              placeholder="请输入密码"
              type="password"
            ></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword" class="form-item">
            <el-input
              v-model="form.confirmPassword"
              placeholder="请再次输入密码"
              type="password"
            ></el-input>
          </el-form-item >

          <el-form-item label="出生日期" prop="birthTime" class="form-item">
          <el-date-picker
          v-model="form.birthTime"
    type="date"
    placeholder="选择日期"
    format="YYYY-MM-DD"
      style="width: 100%;"
      :picker-options="pickerOptions">
    </el-date-picker>
  </el-form-item>

  <el-form-item label="选择性别" prop="xingbie" class="form-item">
    <div class="radio">
      <el-radio-group v-model="form.selectedGender" style="size: 100px;">
                  <el-radio label="男" class="custom-radio ">男</el-radio>
                  <el-radio label="女" class="custom-radio ">女</el-radio>
                
                </el-radio-group>
              </div>
  </el-form-item>

          <el-form-item label="选择身份" prop="credit" class="form-item">
            <div class="radio">
                <el-radio-group v-model="form.selectedshenf">
                  <el-radio label="1">患者</el-radio>
                  <el-radio label="2">医生</el-radio>
                  <el-radio label="3">药师</el-radio>
                  <el-radio label="4">管理</el-radio>
                </el-radio-group>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit()" class="register-button">注册</el-button>
            <el-button @click="onReset" class="register-button">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      </div>
      </el-card>
    </div>
    <div style="background-color: rgb(39,39,39);height: 250px;">
                <el-container>
                    <el-aside  style="margin-left: 40px;">
                        <p style="font-size: 16px; font-weight: bolder;color: #eee;">关于我们</p>
                        <p style="font-size: 12px;color: rgb(149, 149, 149);">医院概况  联系我们</p>
                        <p style="font-size: 12px;color: rgb(149, 149, 149);">常见问题  意见反馈</p>
                        <p style="font-size: 12px;color: rgb(149, 149, 149);">法律条款  关于我们</p>
                        <p style="font-size: 16px; font-weight: bolder;color: #eee;">关注我们</p>
                        <p style="font-size: 12px;color: rgb(149, 149, 149);">qq群:2824444900</p>
                        <!-- <p style="font-size: 12px;color: rgb(149, 149, 149);">qq群:2824444900</p> -->
                    </el-aside>
                    <el-main style="margin-left: 10px;">
                    <div  style="font-style: italic;font-size: 27px;color:rgb(255,255,255);font-weight: bolder !important;margin-left: 130px;margin-top: 20px;">医院预约管理系统</div>
                    <div style="font-size: 12px; color: rgb(149, 149, 149); font-weight: bolder; margin-left: 130px; margin-top: 10px;">由高教社联手网易推出，让每一个有提升愿望的用户能够学到中国知名高校的课程，并获得认证。</div>
                    <div style="font-size: 12px; color: rgb(149, 149, 149); margin-left: 130px; margin-top: 10px;">
                        网上有害信息举报（涉未成年人）：网站  邮箱（涉未成年人） youdao_jubao@rd.netease.com
                    </div>
                    <div style="font-size: 12px; color: rgb(149, 149, 149); margin-left: 130px; margin-top: 5px;">
                        粤B2-20090191-26 | 京ICP备12020869号-2 | 京公网安备44010602000207
                    </div>
                </el-main>
                </el-container>
            
          </div>
  </template>
  
  <script>
  import { reactive,ref } from "vue";
  import axios from "axios";
import {useRoute,useRouter} from 'vue-router'

  export default {
    name: "register",
    setup() {
      
      const router = useRouter();
      const registerForm = ref(null);
      let user2 = {
    doctorId: 0,
  name: "",
  specialty: "",
  phoneNumber: "",
  email: "",
  roomNumber: "",
  password: ""
  };

  let user3={
    patientId: 0,
    name: "",
    gender: "",
    birthDate: "",
    phoneNumber: "",
    email: "",
    address: "",
    password: ""
  };
  
      let form = reactive({
        username: "",
        email: "",
        telephone:"",
        password: "",
        confirmPassword: "",
        birthTime:"",
        selectedGender:"0",
        selectedshenf:"1",
      });
      // 用户接口
      const user = ref({
      userPhone: "",
      password: "",
      userEmail: "",
      name: "",
      gender: 0,
      birthDate: "",
      imageFile:null,
    });
    
    const imageUrl= ref(""); // 图片预览 URL
    const selectedFile= ref(null); // 选中的文件对象
    const beforeUpload=(file) => {
        // 检查文件类型和大小
        const isImage = file.type.startsWith("image/");
        const isLt2M = file.size / 1024 / 1024 < 2;
  
        if (!isImage) {
         alert("只能上传图片文件！");
        }
        if (!isLt2M) {
          alert("上传图片大小不能超过 2MB！");
        }
        console.log("图片文件的类型:",selectedFile.value)
        return isImage && isLt2M;
      };
      const handleUploadSuccess=(response)=> {
        this.$message.success("上传成功！");
        // 处理上传成功的逻辑
      };
     const  customRequest=({ file })=> {
        // 将选中的文件存储，用于后续上传
        const reader = new FileReader();
        reader.onload = () => {
          imageUrl.value = reader.result; // 图片预览
        };
        reader.readAsDataURL(file);
        selectedFile.value = file;
      };


      const rules = {
        username: [
          { required: true, message: "请输入名字", trigger: "blur" },
          {
            pattern: /^[\u4e00-\u9fa5]{1,}$/, 
            message: "请输入正确的汉字", 
            trigger: "blur"
          },
        ],
        telephone: [
        { required: true, message: "请输入手机号", trigger: "blur" },
        { 
          pattern: /^1[3-9]\d{9}$/, 
          message: "请输入正确的11位手机号", 
          trigger: "blur" 
        },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, message: "密码至少6个字符", trigger: "blur" },
        ],
        confirmPassword: [
          { required: true, message: "请确认密码", trigger: "blur"  },
          {
            validator: (rule, value, callback) => {
              if (value !== form.password) {
                callback(new Error("两次密码输入不一致"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        birthTime: [
  { required: true, message: "请选择出生日期", trigger: "change" },
  {
    validator: (rule, value, callback) => {
      if (!value) {
        callback(new Error("请选择出生日期"));
      } else {
        const parsedDate = new Date(value);
        if (isNaN(parsedDate.getTime())) {
          callback(new Error("日期格式无效"));
        } else {
          const today = new Date();
          const age = today.getFullYear() - parsedDate.getFullYear();
          const monthDifference = today.getMonth() - parsedDate.getMonth();
          const dayDifference = today.getDate() - parsedDate.getDate();

          if (
            age < 18 ||
            (age === 18 && (monthDifference < 0 || (monthDifference === 0 && dayDifference < 0)))
          ) {
            callback(new Error("您必须年满18岁"));
          } else {

            callback();
          }
        }
      }
    },
    trigger: "blur",
  },
],
selectedGender: [
  { required: true, message: "请选择性别", trigger: "change" },
  {
    validator: (rule, value, callback) => {
      const validGenders = ["0", "1"]; // 定义合法性别选项
      if (!validGenders.includes(value)) {
        callback(new Error("请选择有效的性别"));
      } else {
        callback(); // 验证通过
      }
    },
    trigger: "change",
  },
],
      };
  
      const onSubmit = () => {
      registerForm.value.validate((valid) => {
        if (valid) {
          user.value.name=form.username;
          user.value.userEmail=form.email;
          user.value.birthDate=form.birthTime;
          user.value.gender=form.selectedGender;
          user.value.password=form.password;
          user.value.userPhone=form.telephone;
          user.imageFile=selectedFile.value;
          if(form.selectedshenf=="1"){
                user3.name=form.username;
              user3.password=form.password;
              user3.gender=form.selectedGender;
              user3.birthDate="2000-06-06";
              user3.phoneNumber=form.telephone;
              user3.patientId=234;
              user3.address="青岛市市南区某路";
              user3.email="zhouba@example.com";
              console.log(user3);
              axios
                .post("http://zhsj.autumnclouds.cn/patient", user3)
                .then((response) => {
                  // 注册成功
                  console.log("你没得");
                  console.log(response);
                  alert("注册成功!")
                  router.push("/")
                })
                .catch((error) => {
                  alert("注册失败!");
                });
          }else if(form.selectedshenf=="2"){
                user2.name=form.username;
                user2.password=form.password;
                user2.phoneNumber=form.telephone;
                user2.doctorId=0;
                console.log(user2);
              axios
                .post("http://zhsj.autumnclouds.cn/doctor", user2)
                .then((response) => {
                  // 注册成功
                  console.log(response.data.data.token);
                  alert("注册成功!")
                  router.push("/")
                })
                .catch((error) => {
                  // 注册失败
                  alert("注册失败!");
                });
          }
          
         
        } else {
          alert("请完善表单信息！");
        }
      });
    };

    const onReset = () => {
      registerForm.value.resetFields();
      form.selectedGender="";
    };
  
  
      return {
        form,
        registerForm,
        rules,
        onSubmit,
        onReset,
        imageUrl,
        selectedFile,
        beforeUpload,
        handleUploadSuccess,
        customRequest,
        // handleConfirm,
      };
    },
  };
  </script>
  
  <style scoped>
  #app {
    display: flex;
    justify-content: center;
    align-items: top;
    
    height: 100vh;
    background: linear-gradient(135deg, hsl(255, 255, 255), #acb6e5);
    margin: 0;
  }
  .form-item {
  width: 100%; /* 确保所有表单项内容宽度一致 */
}

.el-input,
.el-date-picker {
  width: 100%; /* 设置输入框和日期选择器的宽度 */
}
  .register-card {
    margin-top: 50px;
    width: 800px;
    padding: 20px 30px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    border-radius: 10px;
    height: 500px;
    
  }
  
  .title {
    text-align: center;
    font-size: 1.5em;
    margin-bottom: 20px;
  }
  
  .register-form {
    margin-top: 10px;
  }
  .radio{
    
    display: flex;
    justify-content: center;
  }
  .register-button {
    display: block;
    width: 20%;
    height: 50px;
    margin-right: 60px;
    padding: 10px 15px;
    font-size: 16px;
    color: #f4f0f0;
    background: linear-gradient(135deg, #d35ddd, #2a4395);
    border: none;
    border-radius: 5px;
    cursor: pointer;
    transition: transform 0.3s ease, box-shadow 0.3s ease;
  }
  
  .register-button:hover {
    transform: scale(1.05); /* 放大效果 */
    box-shadow: 0px 10px 20px rgba(0, 0, 0, 0.2);
  }
  /* 调整单选框图标大小 */
.custom-radio .el-radio__input {
  transform: scale(1.5); /* 设置缩放比例 */
}

/* 调整文字的大小 */
.custom-radio .el-radio__label {
  font-size: 26px; /* 调整文字大小 */
}

.avatar-upload {
  flex: 0 0 auto; /* 确保左侧固定宽度 */
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center; /* 垂直居中 */
  margin-right: 20px; /* 与表单右侧的间距 */
}
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
  }
  .avatar {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    
  }
  .upload-demo {
    margin-bottom: 20px;
  }
  .register-content {
    
  display: flex;
}
.form-container {
  flex: 1;
}
  </style>